package com.jy.admin.services.cashPocket;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.DateUtil;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.ApiTypeEnum;
import com.jy.admin.enums.CbCashCollectionTagEnum;
import com.jy.admin.enums.OrderStatusEnum;
import com.jy.admin.enums.OrderSyncStatusEnum;
import com.jy.admin.jobs.BaseJobHandler;
import com.jy.admin.services.BaseCrawlerService;
import com.jy.admin.services.cashPocket.vo.*;
import com.jy.bo.common.conf.util.HttpUtil;
import com.robert.vesta.util.IdUtils;
import okhttp3.*;
import org.apache.commons.codec.binary.Base64;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.io.*;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

//import sun.misc.BASE64Encoder;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2022/1/10
 * Time: 8:49 下午
 */
@Service
public class CbCashService extends BaseCrawlerService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CbCashService.class);

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeMerchantDao merchantDao;

    @Autowired
    private CeCommentPushLogDao commentPushLogDao;

    @Autowired
    private CeAgentAccountDao agentAccountDao;


    @PostConstruct
    public void init() {
        BaseJobHandler.merchantAndServiceMap.put("okloan", this);
        BaseJobHandler.merchantAndServiceMap.put("lendking", this);
        BaseJobHandler.merchantAndServiceMap.put("cashpear", this);
        BaseJobHandler.merchantAndServiceMap.put("cashlemon", this);
        BaseJobHandler.merchantAndServiceMap.put("finloan", this);
    }

    @Override
    public boolean hasLogin(CeAgentAccountEntity agentAccount) {
        if (apolloConfigUtil.isLoginStatusUseCache()) {
            return agentAccount.getLoginStatus() == 1;
        }

        if (agentAccount.getLoginStatus() == 2) {
            LOGGER.error("== 账号 token不可用 ==,account:{}", agentAccount.getAccount());
            return false;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/index.php?r=work-desk%2Fadmin-collection-order-list&loan_collection_order_id=&order_id=&name=&loan_phone=&overdue_day=&status=&customer_type=&s_last_collection_time=&e_last_collection_time=&s_true_pay_time=&e_true_pay_time=&s_dispatch_time=&e_dispatch_time=&search_submit=screen";
        LOGGER.info("== 检测登陆 开始请求订单列表 ==,url:{}", url);

        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);
        if (StringUtils.isEmpty(result)) {
            LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
            agentAccount.setLoginStatus(2);
            agentAccountDao.updateByPrimaryKey(agentAccount);
            return false;
        }

        try {
            Document doc = Jsoup.parse(result);
            Element info_table = doc.getElementById("info_table");
            if (info_table == null) {
                LOGGER.error("== 请求接口数据出错 当前账号token无效==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType());
                agentAccount.setLoginStatus(2);
                agentAccountDao.updateByPrimaryKey(agentAccount);
                return false;
            }

        } catch (Exception e) {
            LOGGER.error("== 请求接口数据出错 当前账号登陆异常==，account:{},api:{}", agentAccount.getAccount(), ApiTypeEnum.order_list.getType(), e);
        }

        return true;
    }

    @Override
    public void refresh(CeAgentAccountEntity agentAccount) {

        updateOrderList(agentAccount);
        updateOrderDetailInfo(agentAccount);
    }

    @Override
    public void updateOrderList(CeAgentAccountEntity agentAccount) {
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        String url = merchant.getApiDomain() + "/index.php?r=work-desk%2Fadmin-collection-order-list&loan_collection_order_id=&order_id=&name=&loan_phone=&overdue_day=&status=20&customer_type=&s_last_collection_time=&e_last_collection_time=&s_true_pay_time=&e_true_pay_time=&s_dispatch_time=&e_dispatch_time=&search_submit=screen&page_size=500";
        LOGGER.info("== 开始请求订单列表 ==,url:{}", url);
        Map<String, String> headers = getHeaders(agentAccount);
        Map<String, String> params = Maps.newHashMap();
        String result = HttpUtil.getPage(url, params, headers);

        Document document = Jsoup.parse(result);
        Elements trs = document.select("table").select("tr");

        List<CbCashTableElement> items = new ArrayList<>();
        for (int i = 1; i < trs.size(); i++) {
            CbCashTableElement element = new CbCashTableElement();
            Elements tds = trs.get(i).select("td");

            for (int j = 0; j < tds.size(); j++) {
                String value = tds.get(j).childNodes().get(0).toString();
                if (j == 1) {
                    element.setAppName(value);
                } else if (j == 2) {
                    element.setOrderId(value);
                } else if (j == 3) {
                    element.setLoanOrderId(value);
                } else if (j == 4) {
                    element.setName(value);
                } else if (j == 5) {
                    element.setPhone(value);
                } else if (j == 7) {
                    element.setAmount(value);
                } else if (j == 8) {
                    element.setOverdueDays(value);
                } else if (j == 9) {
                    element.setLateFee(value);
                } else if (j == 10) {
                    element.setRepaymentDate(value);
                } else if (j == 12) {
                    element.setPaidStatus(value);
                } else if (j == 14) {
                    element.setPaidAmount(value);
                } else if (j == 19) {
                    element.setIsReloan(value.equalsIgnoreCase("old") ? "2" : "1");
                }

            }
            items.add(element);

        }

        //查询今天该账号的所有有效订单
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());

        //如果为空则全部选择插入，这个其实就是初始化数据
        if (CollectionUtils.isEmpty(activeOrders)) {
            LOGGER.info("==当天没有数活跃数据 开始插入新数据 ==，size:{}", items.size());
            items.forEach(item -> {
                try {
                    String collectionNo = IdUtils.genId() + "";
                    CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                            .setAgentCode(agentAccount.getAgentCode())
                            .setMerchantCode(agentAccount.getMerchantCode())
                            .setOrderNo(item.getLoanOrderId())
                            .setOrderInfo(JsonStream.serialize(item))
                            .setStatus(OrderStatusEnum.active.getStatus())
                            .setCreateDt(new Date())
                            .setCollectionNo(collectionNo);
                    ordersDao.insert(ceOrdersEntity);
                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.getLoanOrderId(), e);
                }
            });
        } else {
            //更新数据
            LOGGER.info("==当天已经有数据 ==，size:{}", activeOrders.size());
            Map<String, CeOrdersEntity> activeOrdersMap = new HashMap<>();
            Set<String> newOrdersSet = new HashSet<>();
            activeOrders.forEach(o -> {
                activeOrdersMap.put(o.getOrderNo(), o);
            });
            items.forEach(item -> {
                String loanId = item.getLoanOrderId();
                newOrdersSet.add(loanId);
            });

            //如果更新之后发现有新的订单了，则继续插入
            items.forEach(item -> {
                try {
                    String loanId = item.getLoanOrderId();
                    if (!activeOrdersMap.containsKey(loanId)) {
                        LOGGER.info("==更新的时候发现有新的订单==,account:{},loanId:{}", agentAccount.getAccount(), loanId);
                        CeOrdersEntity ceOrdersEntity = new CeOrdersEntity()
                                .setAgentCode(agentAccount.getAgentCode())
                                .setMerchantCode(agentAccount.getMerchantCode())
                                .setOrderNo(loanId)
                                .setOrderInfo(JsonStream.serialize(item))
                                .setStatus(OrderStatusEnum.active.getStatus())
                                .setCreateDt(new Date())
                                .setCollectionNo(IdUtils.genId() + "");
                        ordersDao.insert(ceOrdersEntity);
                    }

                } catch (Exception e) {
                    LOGGER.error("== 插入数据发生异常 ==,account:{},loanId:{}", agentAccount.getAccount(), item.getOrderId(), e);
                }
            });

            //如果跟新之后发现数据比原来的少了，则需要更新订单状态
            activeOrdersMap.keySet().forEach(activeOrderNo -> {
                try {
                    if (!newOrdersSet.contains(activeOrderNo)) {
                        LOGGER.info("== 更新的时候发现有订单消失 目前认为是订单状态发生了改变 ==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo);
                        CeOrdersEntity ceOrdersEntity = activeOrdersMap.get(activeOrderNo);
                        if (ceOrdersEntity.getStatus().equals(OrderStatusEnum.active.getStatus())) {
                            ceOrdersEntity.setStatus(OrderStatusEnum.updated.getStatus());
                            ordersDao.updateByPrimaryKey(ceOrdersEntity);
                        }
                    }
                } catch (Exception e) {
                    LOGGER.info("==更新的时候发现有订单 异常==,account:{},loanId:{}", agentAccount.getAccount(), activeOrderNo, e);
                }
            });
        }

        LOGGER.info("== 订单刷新处理完成 ==");

    }

    @Override
    public void updateOrderDetailInfo(CeAgentAccountEntity agentAccount) {
        List<CeOrdersEntity> activeOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.active.getStatus());
        if (CollectionUtils.isEmpty(activeOrders)) {
            return;
        }

        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());

        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();

        activeOrders.forEach(order -> {

            try {
                boolean hasDetailData = order.getDetailStatus() == 1;

                Any orderInfoJson = JsonIterator.deserialize(order.getOrderInfo());
                String orderId = orderInfoJson.get("orderId").toString();
                String loanOrderId = orderInfoJson.get("loanOrderId").toString();


                Map<String, String> infoMap = new HashMap<>();
                String baseInfoUrl = merchant.getApiDomain() + "/index.php?r=work-desk%2Fcollection-view&base_info=base_info&order_id=" + orderId;
                String baseInfo = HttpUtil.getPage(baseInfoUrl, params, headers);
                infoMap.put("repaymentInfo", baseInfo);

                String remainMoney = new BigDecimal(JsonIterator.deserialize(baseInfo).get("repayInfo").get("surplus_money").toString()).divide(new BigDecimal(100)).toString();
                updateRemainMoney(order.getCollectionNo(), remainMoney);
                LOGGER.info("== 获取成功 repaymentInfo==");


                if (!hasDetailData) {
                    List<String> images = Lists.newArrayList();
                    CeOrdersDetailEntity personalInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "personalInfo", order.getOrderNo());
                    if (personalInfoDetail == null) {
                        String url = merchant.getApiDomain() + "/index.php?r=work-desk%2Fcollection-view&order_id=" + orderId + "&loan_order_id=" + loanOrderId;
                        String result = HttpUtil.getPage(url, params, headers);
                        Document document = Jsoup.parse(result);
                        Elements tables = document.select("table");
                        Elements trs = tables.get(0).select("tr");
                        CbCashBasicData cbCashBasicData = new CbCashBasicData();
                        for (int i = 1; i < trs.size(); i++) {
                            Elements tds = trs.get(i).select("td");
                            for (int j = 0; j < tds.size(); j++) {
                                Element element = tds.get(j);
                                if (tds.get(j).childNodes().size() <= 0) {
                                    continue;
                                }
                                String value = tds.get(j).childNodes().get(0).toString();

                                if (i == 1 && j == 2) {
                                    cbCashBasicData.setGender(value);
                                } else if (i == 2 && j == 0) {
                                    cbCashBasicData.setBirthDay(value);
                                } else if (i == 2 && j == 1) {
                                    cbCashBasicData.setEducation(value);
                                } else if (i == 2 && j == 2) {
                                    cbCashBasicData.setMarriage(value);
                                } else if (i == 3 && j == 1) {
                                    cbCashBasicData.setPanNo(value);
                                } else if (i == 4 && j == 0) {
                                    cbCashBasicData.setCompanyName(value);
                                } else if(i == 6 && j==0){
                                    List<Node> nodes = tds.get(j).childNodes();
                                    for (int k = 0; k < nodes.size(); k++) {
                                        String s = nodes.get(k).toString();
                                        if (StringUtils.isNotEmpty(s)) {
                                            Document adoc = Jsoup.parse(s);
                                            Elements achildTrs = adoc.select("img");
                                            if (achildTrs.size() > 0) {
                                                String src = achildTrs.get(0).attributes().get("src");
                                                cbCashBasicData.setFacePhoto(src);
                                            }
                                        }

                                    }
                                } else if(i == 6 && j==1){
                                    List<Node> nodes = tds.get(j).childNodes();
                                    List<String> list = Lists.newArrayList();
                                    for (int k = 0; k < nodes.size(); k++) {
                                        String s = nodes.get(k).toString();
                                        if (StringUtils.isNotEmpty(s)) {
                                            Document adoc = Jsoup.parse(s);
                                            Elements achildTrs = adoc.select("img");
                                            if (achildTrs.size() > 0) {
                                                String src = achildTrs.get(0).attributes().get("src");
                                                list.add(src);
                                            }
                                        }
                                    }
                                    cbCashBasicData.setCardImage(list);
                                }else if (i == 7 && j == 2) {
                                    cbCashBasicData.setEmail(value);
                                }


                            }

                            LOGGER.info("== adaf ==");
                        }
                        LOGGER.info("== 获取成功 personalInfo==");
                        infoMap.put("personalInfo", JsonStream.serialize(cbCashBasicData));

                        images.addAll(cbCashBasicData.getCardImage());
                        images.add(cbCashBasicData.getFacePhoto());
                    } else {
                        personalInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(personalInfoDetail);
                    }

                    CeOrdersDetailEntity imagesDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "images", order.getOrderNo());
                    if (imagesDetail == null) {
                        if (images.size() == 0){
                            Any deserialize = JsonIterator.deserialize(personalInfoDetail.getDetailInfo());
                            List<Any> cardImage = deserialize.get("cardImage").asList();
                            cardImage.forEach(v->{
                                images.add(v.toString());
                            });
                            images.add(deserialize.get("facePhoto").toString());
                        }
                        infoMap.put("images", JsonStream.serialize(images));

                    }else {
                        imagesDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(imagesDetail);
                    }


                    CeOrdersDetailEntity emergencyContactInfoDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "emergencyContactInfo", order.getOrderNo());
                    if (emergencyContactInfoDetail == null) {
                        String emergencyContactUrl = merchant.getApiDomain() + "/index.php?r=work-desk%2Fcollection-view&get_jxl=base_info&order_id=" + orderId;
                        String emergencyContactInfo = HttpUtil.getPage(emergencyContactUrl, params, headers);
                        LOGGER.info("== 获取成功 emergencyContactInfo==");
                        infoMap.put("emergencyContactInfo", emergencyContactInfo);
                    } else {
                        emergencyContactInfoDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(emergencyContactInfoDetail);
                    }

                    CeOrdersDetailEntity contactUrlDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(merchant.getMerchantCode(), "contactUrl", order.getOrderNo());
                    if (contactUrlDetail == null) {
                        String contactListUrl = merchant.getApiDomain() + "/index.php?r=work-desk%2Fcollection-view&contact_list=base_info&order_id=" + orderId;
                        String addressBook = HttpUtil.getPage(contactListUrl, params, headers);
                        LOGGER.info("== 获取成功 addressBook==");
                        List<Any> contactList;
                        try {
                            contactList = JsonIterator.deserialize(addressBook).get("loan_mobile_contacts_list").asList().get(0).asList();
                            if (CollectionUtils.isNotEmpty(contactList)) {
                                JSONArray contacts = new JSONArray();
                                for (Any vo : contactList) {
                                    JSONObject j1 = new JSONObject();
                                    if (vo.get("name") == null) {
                                        j1.put("name", "no");
                                    } else {
                                        j1.put("name", vo.get("name").toString());
                                    }

                                    if (vo.get("mobile") == null) {
                                        j1.put("phone", "no");
                                    } else {
                                        j1.put("phone", vo.get("mobile").toString());
                                    }
                                    contacts.add(j1);
                                }
                                JSONObject jsonData = new JSONObject();
                                jsonData.put("contacts", contacts);

                                String contactUrl = uploadContact(loanOrderId, jsonData.toString());
                                LOGGER.info("== 上传通讯录，得到地址 ==,url:{}", contactUrl);
                                infoMap.put("contactUrl", contactUrl);
                            }
                        } catch (Exception e) {
                            LOGGER.error("== 通讯录转换错误 ==", e);
                        }
                    } else {
                        contactUrlDetail.setGmtModified(new Date());
                        ordersDetailDao.updateByPrimaryKey(contactUrlDetail);
                    }

                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        if (byKeyAndMerchantAndOrderNo == null) {
                            CeOrdersDetailEntity ordersDetailEntity = new CeOrdersDetailEntity()
                                    .setOrderNo(order.getOrderNo())
                                    .setMerchantCode(order.getMerchantCode())
                                    .setDataKey(k)
                                    .setDetailInfo(infoMap.get(k));
                            ordersDetailDao.insert(ordersDetailEntity);
                        } else {
                            byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                            ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                        }

                    });

                    order.setSyncStatus(OrderSyncStatusEnum.waiting.getStatus());
                } else {
                    infoMap.keySet().forEach(k -> {
                        CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), k, order.getOrderNo());
                        byKeyAndMerchantAndOrderNo.setDetailInfo(infoMap.get(k));
                        ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);
                    });
                }

                order.setDetailStatus(1);
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 程序处理有异常 ==", e);
                order.setDetailStatus(2);
                ordersDao.updateByPrimaryKey(order);
            }
        });

        LOGGER.info("== 程序处理完成 ==");
    }

    @Override
    public void compostCollectionData(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== compostCollectionData ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== compostCollectionData  没有需要同步的订单 ==，agentCode:{},syncStatus:{}", agentAccount.getAgentCode(), OrderSyncStatusEnum.waiting.getStatus());
            return;
        }

        LOGGER.info("== compostCollectionData  需要同步的订单 ==，size:{},account:{}", todayListBySyncStatusAndAgent.size(), agentAccount.getAccount());

        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                LOGGER.info("== 构建推送信息 基础信息 开始==,collectionNo:{},syncStatus:{}", order.getCollectionNo(), order.getSyncStatus());
                Any orderDetail = JsonIterator.deserialize(order.getOrderInfo());
                String appName = orderDetail.get("appName").toString().trim();
                ClOrderReceiveRequest request = new ClOrderReceiveRequest()
                        .setOrderBillNo(order.getCollectionNo())
                        .setTradeNo(order.getCollectionNo())
                        .setProductType(appName)
                        .setAppName(appName)
                        .setOriginOrderNo(order.getOrderNo())
                        .setProductCode(appName)
                        .setAccount(order.getAgentCode())
                        .setAccount_id(agentAccount.getId())
                        .setClientCode(order.getMerchantCode())
                        .setUserCode(IdUtils.genId() + "");

                CeOrdersDetailEntity emergencyContactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "emergencyContactInfo", order.getOrderNo());
                Any emergencyContactInfoJson = JsonIterator.deserialize(emergencyContactInfo.getDetailInfo());

                CeOrdersDetailEntity personalInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "personalInfo", order.getOrderNo());
                Any personalInfoJson = JsonIterator.deserialize(personalInfo.getDetailInfo());

                CeOrdersDetailEntity repaymentInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any repaymentInfoJson = JsonIterator.deserialize(repaymentInfo.getDetailInfo());

                CeOrdersDetailEntity contactUrl = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "contactUrl", order.getOrderNo());
                Any contactUrlJson = JsonIterator.deserialize(contactUrl.getDetailInfo());

                CeOrdersDetailEntity imagesDetail = ordersDetailDao.getByKeyAndMerchantAndOrderNo(order.getMerchantCode(), "images", order.getOrderNo());
                Any imagesJson = JsonIterator.deserialize(imagesDetail.getDetailInfo());

                String borrowCapital = new BigDecimal(repaymentInfoJson.get("repayInfo").get("amount").toString()).divide(new BigDecimal(100)).toString();
                String overdueDays = repaymentInfoJson.get("repayInfo").get("overdue_day").toString();
                String lateFee = new BigDecimal(repaymentInfoJson.get("repayInfo").get("overdue_fee").toString()).divide(new BigDecimal(100)).toString();
                Any isReloan = orderDetail.get("isReloan");

                if (lateFee.equals("0E-8")) {
                    lateFee = "0";
                }
                String overdueRatio = "0";
                String serviceFee = new BigDecimal(repaymentInfoJson.get("repayInfo").get("cost_fee").toString()).divide(new BigDecimal(100)).toString();
                LOGGER.info("== 构建推送信息 计算逾期罚息利率 开始==,borrowCapital:{}，overdueDays:{}.lateFee:{}", borrowCapital, overdueDays, lateFee);
                if (!overdueDays.equals("0")) {
                    overdueRatio = new BigDecimal(lateFee).divide(new BigDecimal(overdueDays), 2, BigDecimal.ROUND_HALF_UP).divide(new BigDecimal(borrowCapital).add(new BigDecimal(serviceFee)), 4, BigDecimal.ROUND_HALF_UP).toString();
                }

                LOGGER.info("== 构建推送信息 订单信息 开始==,collectionNo:{}", order.getCollectionNo());
                String paidAmount = new BigDecimal(repaymentInfoJson.get("repayInfo").get("true_total_money").toString()).divide(new BigDecimal(100)).toString();
                ClOrderInputVo orderInputVo = new ClOrderInputVo()
                        .setBorrowType(isReloan.toInt())
                        .setBorrowCapital(new BigDecimal(borrowCapital).add(new BigDecimal(serviceFee)).toString())
                        .setChannel(appName)
                        .setCapitalCode(appName)
                        .setInterest(new BigDecimal(repaymentInfoJson.get("repayInfo").get("interests").toString()).divide(new BigDecimal(100)).toString())
                        .setDeductAmount("0")
                        .setLateFeeRatio(overdueRatio)
                        .setServiceFee(serviceFee)
                        .setLateServiceFee(new BigDecimal(repaymentInfoJson.get("repayInfo").get("overdue_fee").toString()).divide(new BigDecimal(100)).toString())
                        .setReceivedCapital(borrowCapital)
                        .setPaidAmount(paidAmount)
                        .setReceivedDate(repaymentInfoJson.get("repayInfo").get("loan_time").toString())
                        .setRepaymentDate(getLastDayDate(repaymentInfoJson.get("repayInfo").get("plan_fee_time").toString()))
                        .setRemainMoney(new BigDecimal(repaymentInfoJson.get("repayInfo").get("surplus_money").toString()).divide(new BigDecimal(100)).toString())
                        .setTotalMoney(new BigDecimal(repaymentInfoJson.get("repayInfo").get("total_money").toString()).divide(new BigDecimal(100)).toString());

                //surplus_money
                request.setOrderInfo(orderInputVo);

                LOGGER.info("== 构建推送信息 个人信息 开始==,collectionNo:{}", order.getCollectionNo());

                String aadhaarNo = "no-data";
                String pancardNo = personalInfoJson.get("panNo").toString();
                String email = personalInfoJson.get("email").toString();

                String companyCity = "no-data";
                String companyProvince = "no-data";
                String friendName = "no";
                String friendMobile = "no";

                String parentName = "no";
                String parentPhone = "no";

                List<Any> anies = emergencyContactInfoJson.get("jxl_contact").asList();
                String personMobile = "";
                String personName = "";
                for (Any item : anies) {
                    String relationType = item.get("relation").toString().toLowerCase();
                    if ("parent".equalsIgnoreCase(relationType)) {
                        parentName = item.get("name").toString();
                        parentPhone = item.get("phone").toString();
                    } else if ("oneself".equalsIgnoreCase(relationType)) {
                        personMobile = item.get("phone").toString();
                        personName = item.get("name").toString();
                    } else {
                        friendName = item.get("name").toString();
                        friendMobile = item.get("phone").toString();
                    }
                }

                if ("no".equalsIgnoreCase(parentName)) {
                    if (anies.size() >= 2) {
                        parentName = anies.get(1).get("name").toString();
                        parentPhone = anies.get(1).get("phone").toString();
                    }

                    if (anies.size() >= 3) {
                        friendName = anies.get(2).get("name").toString();
                        friendMobile = anies.get(2).get("phone").toString();
                    }

                }
                List<String> images = new ArrayList<>();
                imagesJson.forEach(v -> {
                    images.add(v.toString());
                });
                ClUserInfoInputVo userInfoInputVo = new ClUserInfoInputVo()
                        .setUserLanguage("")
                        .setAadhaarNo(aadhaarNo)
                        .setPanCardNo(pancardNo)
                        .setAddress(personalInfoJson.get("companyName").toString())
                        .setBirthday(personalInfoJson.get("birthDay").toString())
                        .setCity(companyCity)
                        .setEmail(email)

                        .setContact1Mobile(parentPhone)
                        .setContact1Name(parentName)
                        .setContact1Relative(1)

                        .setContact2Mobile(friendMobile)
                        .setContact2Name(friendName)
                        .setContact2Relative(6)

                        .setEducation(0)
                        .setKycNo(aadhaarNo)
                        .setMobile(personMobile)

                        .setMarriedStatus(0)
                        .setName(personName)
                        .setPinCode("no")
                        .setState(companyProvince)
                        .setImages(images)
                        .setSex("female".equals(personalInfoJson.get("gender").toString()) ? 0 : 1)
                        .setContactUrl(contactUrlJson.toString());

                request.setUserInfo(userInfoInputVo);

                LOGGER.info("== 构建推送信息 完成==,collectionNo:{}", order.getCollectionNo());

                CePushLogEntity pushLogEntity = pushLogDao.selectByCollectionNo(order.getCollectionNo());
                if (pushLogEntity == null) {
                    pushLogEntity = new CePushLogEntity()
                            .setCollectionNo(order.getCollectionNo())
                            .setDetailInfo(JsonStream.serialize(request))
                            .setStatus(1);
                    pushLogDao.insert(pushLogEntity);
                } else {
                    pushLogEntity.setDetailInfo(JsonStream.serialize(request));
                    pushLogDao.updateByPrimaryKey(pushLogEntity);
                }


                LOGGER.info("== 构建推送信息 保存信息完成==,collectionNo:{}", order.getCollectionNo());
                order.setSyncStatus(OrderSyncStatusEnum.data_ready.getStatus());
                ordersDao.updateByPrimaryKey(order);
            } catch (Exception e) {
                LOGGER.error("== 构建推送信息 发生异常==,collectionNo:{}", order.getCollectionNo(), e);
                order.setSyncStatus(OrderSyncStatusEnum.data_fail.getStatus());
                ordersDao.updateByPrimaryKey(order);
            }
        });

    }

    @Override
    public void pushDataToCollection(CeAgentAccountEntity agentAccount) {
        super.pushDataToCollection(agentAccount);
    }

    @Override
    public void checkOrdersPaidStatus(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 检查订单支付情况 ==");
        List<CeOrdersEntity> waitingPaidCheckOrders = ordersDao.getTodayListByStatusAndAgent(agentAccount.getAgentCode(), OrderStatusEnum.updated.getStatus());
        if (CollectionUtils.isEmpty(waitingPaidCheckOrders)) {
            LOGGER.info("== 检查订单支付情况 没有状态更新的订单==,size:{}", waitingPaidCheckOrders.size());
            return;
        }

        LOGGER.info("== 检查订单支付情况==,size:{}", waitingPaidCheckOrders.size());
        CeMerchantEntity merchant = merchantDao.queryMerchantByCode(agentAccount.getMerchantCode());
        Map<String, String> headers = getHeaders(agentAccount);
        LOGGER.info("== 构建header ==,header:{}", JsonStream.serialize(headers));

        Map<String, String> params = Maps.newHashMap();
        waitingPaidCheckOrders.forEach(order -> {
            try {
                String orderId = JsonIterator.deserialize(order.getOrderInfo()).get("orderId").toString();
                String baseInfoUrl = merchant.getApiDomain() + "/index.php?r=work-desk%2Fcollection-view&base_info=base_info&order_id=" + orderId;
                String baseInfo = HttpUtil.getPage(baseInfoUrl, params, headers);

                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                byKeyAndMerchantAndOrderNo.setDetailInfo(baseInfo);
                ordersDetailDao.updateByPrimaryKey(byKeyAndMerchantAndOrderNo);

                Any deserialize = JsonIterator.deserialize(baseInfo);

                if ("0".equals(deserialize.get("repayInfo").get("surplus_money").toString().trim()) || "repay complete".equals(deserialize.get("repayInfo").get("ulor_status").toString())) {
                    order.setSyncStatus(OrderSyncStatusEnum.need_pay_update.getStatus());
                    order.setStatus(OrderStatusEnum.paid_update.getStatus());
                    ordersDao.updateByPrimaryKey(order);
                } else {
                    order.setStatus(OrderStatusEnum.removed.getStatus());
                    order.setSyncStatus(OrderSyncStatusEnum.need_remove.getStatus());
                    ordersDao.updateByPrimaryKey(order);
                }
            } catch (Exception e) {
                LOGGER.error("== 检查还款订单异常 ==,orderNo:{}", order.getOrderNo(), e);
            }
        });


    }

    @Override
    public void updatePaidOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("== 开始同步有更新的数据到催收系统 ==");
        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_pay_update.getStatus());
        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
            LOGGER.info("== 开始同步有更新的数据到催收系统 没有还款订单==");
            return;
        }

        LOGGER.info("== 开始同步有更新的数据到催收系统 有还款==,size:{}", todayListBySyncStatusAndAgent.size());
        todayListBySyncStatusAndAgent.forEach(order -> {
            try {
                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
                String paidAmount = new BigDecimal(deserialize.get("repayInfo").get("true_total_money").toString()).divide(new BigDecimal(100)).toString();
                ClRepaymentRequest request = new ClRepaymentRequest()
                        .setDeductAmount("0")
                        .setOrderBillNo(order.getCollectionNo())
                        .setPaidAmount(paidAmount)
                        .setPaidStatus(2)
                        .setPaidType(1)
                        .setRepayBizNo(IdUtils.genId() + "")
                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
                        .setTotalDeductAmount("0")
                        .setTotalPaidAmount(paidAmount)
                        .setTradeNo(order.getCollectionNo());

                HttpHeaders headers = new HttpHeaders();
                headers.set("Content-Type", "application/json;charset=utf-8");

                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl(), requestPush, String.class);
                String responseStr = responseEntity.getBody().toString();
                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl());
                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_success.getStatus());
                } else {
                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
                    order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
                }
            } catch (Exception e) {
                LOGGER.error("=======  推送collection请求结果 error  ======", e);
                order.setSyncStatus(OrderSyncStatusEnum.pay_update_fail.getStatus());
            }
            ordersDao.updateByPrimaryKey(order);
        });

    }

    @Override
    public void updateRemovedOrderToCollection(CeAgentAccountEntity agentAccount) {
        LOGGER.info("==  updateRemovedOrderToCollection 开始同步有更新的数据到催收系统 ==");
//        List<CeOrdersEntity> todayListBySyncStatusAndAgent = ordersDao.getTodayListBySyncStatusAndAgent(agentAccount.getAgentCode(), OrderSyncStatusEnum.need_remove.getStatus());
//        if (CollectionUtils.isEmpty(todayListBySyncStatusAndAgent)) {
//            LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 没有需要移除的订单==");
//            return;
//        }
//
//        LOGGER.info("== 开始同步有更新的数据到催收系统 updateRemovedOrderToCollection 有数据需要移除==,size:{}", todayListBySyncStatusAndAgent.size());
//        todayListBySyncStatusAndAgent.forEach(order -> {
//            try {
//                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNoToday(order.getMerchantCode(), "repaymentInfo", order.getOrderNo());
//                Any deserialize = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
//                String paidAmount = new BigDecimal(deserialize.get("repayInfo").get("true_total_money").toString()).divide(new BigDecimal(100)).toString();
//                ClRepaymentRequest request = new ClRepaymentRequest()
//                        .setDeductAmount("0")
//                        .setOrderBillNo(order.getCollectionNo())
//                        .setPaidAmount(paidAmount)
//                        .setPaidStatus(2)
//                        .setPaidType(1)
//                        .setRepayBizNo(IdUtils.genId() + "")
//                        .setRepayDate(DateUtil.getDate(new Date(), "yyyy-MM-dd HH:mm:ss"))
//                        .setToken("a481e307fd3343c4faca93ADAFb8a3892ee1")
//                        .setTotalDeductAmount("0")
//                        .setTotalPaidAmount(paidAmount)
//                        .setTradeNo(order.getCollectionNo());
//
//                HttpHeaders headers = new HttpHeaders();
//                headers.set("Content-Type", "application/json;charset=utf-8");
//
//                HttpEntity requestPush = new HttpEntity(JsonStream.serialize(request), headers);
//                ResponseEntity responseEntity = new RestTemplate().postForEntity(apolloConfigUtil.getCollectionRepayPushUrl()_remove, requestPush, String.class);
//                String responseStr = responseEntity.getBody().toString();
//                LOGGER.info("=======  推送collection请求结果  ======:{},method:{}", responseStr, apolloConfigUtil.getCollectionRepayPushUrl()_remove);
//                if (JsonIterator.deserialize(responseStr).get("code").toString().equals("0")) {
//                    LOGGER.info("== 开始同步有更新的数据到催收系统 推送还款成功==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_success.getStatus());
//                } else {
//                    LOGGER.error("== 开始同步有更新的数据到催收系统 推送还款失败==,orderNo:{}", order.getOrderNo());
//                    order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//                }
//            } catch (Exception e) {
//                LOGGER.error("=======  推送collection请求结果 error  ======", e);
//                order.setSyncStatus(OrderSyncStatusEnum.remove_failed.getStatus());
//            }
//            ordersDao.updateByPrimaryKey(order);
//        });

    }

    @Override
    public void composeNote(CeCommentPushLogEntity ceCommentPushLogEntity) {

        ceCommentPushLogEntity.setStatus(1);
        commentPushLogDao.updateByPrimaryKey(ceCommentPushLogEntity);
    }


    /**
     * @param ceCommentPushLogEntity
     * @return 1 connected   1-7 willingness-to-repay
     * 1-11 willing to repay
     * 1-5 虚假个人信息
     * 2  no-answer
     * 3  empty-number / halt / shutdown
     * 4  reject / hang-up / pull-black
     */
    @Override
    public boolean sendNote(CeCommentPushLogEntity ceCommentPushLogEntity) {
        LOGGER.info("== 开始同步催记到甲方 ==");

        CbCashCollectionTagEnum currentTag = CbCashCollectionTagEnum.RNR_V2;

        for (CbCashCollectionTagEnum e : CbCashCollectionTagEnum.values()) {
            if (e.getType().equals(ceCommentPushLogEntity.getTargetType())) {
                currentTag = e;
            }
        }

        try {
            CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(ceCommentPushLogEntity.getMerchantCode());
            CeAgentAccountEntity account = agentAccountDao.getByAgentCode(ceCommentPushLogEntity.getAgentCode());

            CeOrdersDetailEntity emergencyContactInfo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(ceCommentPushLogEntity.getMerchantCode(), "emergencyContactInfo", ceCommentPushLogEntity.getOriginNo());
            Any emergencyContactInfoJson = JsonIterator.deserialize(emergencyContactInfo.getDetailInfo());

            Map headers = getHeaders(account);
            Map<String, String> params = Maps.newHashMap();

            List<Any> anies = emergencyContactInfoJson.get("jxl_contact").asList();
            String mobile = "";
            for (Any item : anies) {
                String relationType = item.get("relation").toString().toLowerCase();
                if ("oneself".equalsIgnoreCase(relationType)) {
                    mobile = item.get("phone").toString();
                }
            }


            CeOrdersEntity order = ordersDao.getOneByOrderNo(ceCommentPushLogEntity.getOriginNo());
            String orderId = JsonIterator.deserialize(order.getOrderInfo()).get("orderId").toString();

            String result = HttpUtil.getPage(ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/collect-loan&cuishoutype=thjl&order_id=" + orderId + "&operate_type=1&template_id=-1&content=&remark=" + URLEncoder.encode(ceCommentPushLogEntity.getTargetMsg()) + "&sms_stress_level=1&is_connect=" + currentTag.getCbType() + "&risk_control=" + currentTag.getCbRiskLevel() + "&contact_phone[]=" + mobile + "&promise_repayment_time=", params, headers);
            if (StringUtils.isEmpty(result)) {
                return false;
            }

            return "0".equals(JsonIterator.deserialize(result).get("code").toString());
        } catch (Exception e) {
            LOGGER.error("== cbcash 开始同步催记到甲方 异常==", e);
            return false;
        }
    }

    @Override
    public String updateRepaymentLink(String collectionNo,boolean isReduce) {

        return "";
    }

    @Override
    public String updateExtensionRepaymentLink(String collectionNo,boolean isOpen) {
        return "";
    }

    @Override
    public String addPaymentOrder(String orderNo, String fileName, String fileUrl, String utr, String remark, String amount) {
        CeOrdersEntity oneByOrderNo = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentCode = agentAccountDao.getByAgentCode(oneByOrderNo.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(agentCode.getMerchantCode());

        if (StringUtils.isEmpty(orderNo) || StringUtils.isEmpty(utr) || StringUtils.isEmpty(fileUrl)) {
            LOGGER.info("== pendingOrder params lack ==,orderNo:{}", orderNo);
            return "Add Replenishment Order Failed!";
        }

        String pageUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/add-drop-order";
        Map<String, String> params = Maps.newHashMap();
        Map<String, String> headers = getHeaders(agentCode);
        String result = HttpUtil.getPage(pageUrl, params, headers);

        Document doc = Jsoup.parse(result);
        Elements inputs = doc.select("input");
        Map<String, String> nameAndValue = new HashMap<>();
        inputs.forEach(e -> {
            nameAndValue.put(e.attributes().get("name"), e.attributes().get("value"));
        });

        String csrf = nameAndValue.get("_csrf");

        String date = DateUtil.getDate("yyyy/MM/dd H:mm:0");
        try {
            File img = getFile(fileUrl);
            String s = encodeBase64File(img.getPath());
            String imageUrl = "data:image/png;base64," + s;

            RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("DropOrder[image_url]", imageUrl)
                    .addFormDataPart("DropOrder[order_id]", orderNo)
                    .addFormDataPart("DropOrder[utr]", utr)
                    .addFormDataPart("DropOrder[pay_date]", date)
                    .addFormDataPart("_csrf", csrf)
                    .build();
            String addResult = HttpUtil.postFormData(pageUrl, headers, body);
            if (addResult.contains("Bad Request")) {
                LOGGER.info("== 补单发生错误 ==,orderNo:{}", orderNo);
                ordersDao.updatePendingRecordStatusByCollectionNo(3, oneByOrderNo.getCollectionNo());
                return "Add Replenishment Order Failed!";
            }
            Document pendingRes = Jsoup.parse(addResult);
            Elements h4 = pendingRes.select("h4");
            String msg = h4.get(0).text().toString();
            if (msg.contains("success")) {//提交成功
                LOGGER.info("== 补单提交成功 ==,orderNo:{}", orderNo);
                ordersDao.updatePendingRecordStatusByCollectionNo(4, oneByOrderNo.getCollectionNo());
                return msg;
            } else if (msg.contains("add repeatedly")) {//重复提交
                LOGGER.info("== 补单提交失败,重复提交 ==,orderNo:{}", orderNo);
                ordersDao.updatePendingRecordStatusByCollectionNo(-2, oneByOrderNo.getCollectionNo());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Add Replenishment Order Failed!";
    }

    @Override
    public String queryPaymentOrderResult(String orderNo,String utr) {
        CeOrdersEntity oneByOrderNo = ordersDao.getTodayOneByOrderNo(orderNo);
        CeAgentAccountEntity agentCode = agentAccountDao.getByAgentCode(oneByOrderNo.getAgentCode());
        CeMerchantEntity ceMerchantEntity = merchantDao.queryMerchantByCode(agentCode.getMerchantCode());

        String orderId = JsonIterator.deserialize(oneByOrderNo.getOrderInfo()).get("orderId").toString();
        String repaymentUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk%2Fcollection-view&base_info=base_info&order_id=" + orderId;
        Map<String, String> params = Maps.newHashMap();
        Map<String, String> headers = getHeaders(agentCode);
        String baseInfo = HttpUtil.getPage(repaymentUrl, params, headers);

        Any deserialize = JsonIterator.deserialize(baseInfo);
        if ("0".equals(deserialize.get("repayInfo").get("surplus_money").toString().trim()) || "repay complete".equals(deserialize.get("repayInfo").get("ulor_status").toString())) {
            ordersDao.updatePendingRecordResultTypeByCollectionNo(2, oneByOrderNo.getCollectionNo(), "paid already!");
            return "paid already!";
        } else {

            String queryResultUrl = ceMerchantEntity.getApiDomain() + "/index.php?r=work-desk/drop-order-result&orderId=" + orderId + "&utr=&search_submit=screen";
            String queryResult = HttpUtil.getPage(queryResultUrl, params, headers);
            Document document = Jsoup.parse(queryResult);
            Elements trs = document.select("table").select("tr");

            String message = "";
            for (int i = 1; i < trs.size(); i++) {
                Elements tds = trs.get(i).select("td");

                for (int j = 0; j < tds.size(); j++) {
                    String value = tds.get(j).childNodes().get(0).toString();
                    if (j == 5) {
                        message = value;
                    }

                }

            }
            if (message.equalsIgnoreCase("Paid")) {
                ordersDao.updatePendingRecordResultTypeByCollectionNo(2, oneByOrderNo.getCollectionNo(), "paid already!");
                return "paid already!";
            } else {


                if (trs.size() <= 1) {
                    ordersDao.updatePendingRecordResultTypeByCollectionNo(4, oneByOrderNo.getCollectionNo(), "not received");
                } else {
                    ordersDao.updatePendingRecordResultTypeByCollectionNo(4, oneByOrderNo.getCollectionNo(), message);
                }
                return message;
            }
        }
    }

    @Override
    public String checkOrdersPaid(String orderNo) {
        return null;
    }


    private static File getFile(String url) throws Exception {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;

        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return file;
    }


    public static String getLastDayDate(String date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(DateUtil.getDate(date, "yyyy-MM-dd"));
        c.add(Calendar.DATE, -1);
        Date start = c.getTime();
        return format.format(start);
    }

    public static void main(String[] args) {

//        String TAG = "UploadHelper";
//        MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
//        OkHttpClient client = new OkHttpClient();
//
//        Map headers = new HashMap();
//        headers.put("cookie", "callcenter_session=n7bn67i2mn3v7h2m69m93o210n; _csrf=38ac57dca42580658ad55a8db8a5c527a9a067ccfbb5e1e52d9dd846c4144874a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22A2ATckWQ0l6bzexiQHrwtCIRYyxe3o_F%22%3B%7D");
//        Map<String, String> params = Maps.newHashMap();
//
//        String url = "https://ok-call.moneywoods.in/index.php?r=work-desk%2Fadd-drop-order";
//
//        String imgUrl = "http://dc-oss2.oss-ap-south-1.aliyuncs.com//excel/test/238611757147357753.png";
//        String loanId = "7638166";
//        String code12 = "201512183930";

        //DropOrder[order_id] DropOrder[image_url] DropOrder[utr] DropOrder[pay_date]
        try {
            String date = DateUtil.getDate("yyyy/MM/dd HH:mm:0");
            File img = getFile("https://dc-oss2.oss-ap-south-1.aliyuncs.com/excel/test/236362520355406393.png");
            String s = encodeBase64File(img.getPath());
            String imageUrl = "data:image/png;base64," + s;
            LOGGER.info("== s ==,s:{}", date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return Base64.encodeBase64String(buffer);
    }

}
